package com.skd.mall.auth_server.controller;


import com.alibaba.fastjson.JSON;
import com.skd.common.constant.AuthConstant;
import com.skd.common.constant.SMSConstant;
import com.skd.common.utils.R;
import com.skd.common.vo.MemberVO;
import com.skd.mall.auth_server.fegin.MemberFeginService;
import com.skd.mall.auth_server.fegin.ThirdPartFeginService;
import com.skd.mall.auth_server.vo.LoginVo;
import com.skd.mall.auth_server.vo.UserRegisterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Controller
public class LoginController {
    @RequestMapping({"/","login.html"})
    public String login(){
        return "login";

    }

    @RequestMapping({"reg.html"})
    public String reg(){
        return "reg";

    }

    @Autowired
    private ThirdPartFeginService thirdPartFeginService;
    @Autowired
    private MemberFeginService memberFeginService;

    @Autowired
    private RedisTemplate redisTemplate;
    @ResponseBody
    @RequestMapping("/sms/sendCode")
    /**
     *验证码
     */
    public R sendSmsCode(@RequestParam("phone") String phone){
        //防止60s之内重复发送
        Object redisCode = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + phone);
        if(redisCode != null){
            String s = redisCode.toString();
            if(!"".equals(s)){
                long l = Long.parseLong(redisCode.toString().split("_")[1]);
                if(System.currentTimeMillis() - l <= 60000){
                    //说明验证码发送间隔不足一分钟
                    return R.error(403,"验证码发送频率太快，请稍后重试");
                }
            }
        }
        Random random = new Random();
        // 生成一个0到9999之间的随机整数
        int randomNum = random.nextInt(10000);
        // 将整数转换为字符串，保证是4位数，不足4位前面补0
        String code = String.format("%04d", randomNum);
        thirdPartFeginService.sendSms(phone,code);
        code = code +"_"+System.currentTimeMillis();
        redisTemplate.opsForValue().set(SMSConstant.SMS_CODE_PERFIX+phone,code,10, TimeUnit.MINUTES);
        return R.ok();
    }

    /**
     * 注册
     * @param vo
     * @param result
     * @param model
     * @return
     */
    @PostMapping("/sms/register")
    public String register(@Valid UserRegisterVo vo, BindingResult result, Model model){
        Map<String,String> map = new HashMap<>();
        if(result.hasErrors()){
            // 表示提交的数据不合法
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                String defaultMessage = fieldError.getDefaultMessage();
                map.put(field,defaultMessage);
            }
            System.out.println(map.toString());
            model.addAttribute("error",map);
            return "/reg";
        }else {
            Object o = redisTemplate.opsForValue().get(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
            String code = null;
            if(o!=null){
                code = o.toString();
                code = code.split("_")[0];
            }
            //System.out.println(code);
            if(code == null || !code.equals(vo.getCode())){
                //验证码不正确
                map.put("code","验证码错误");
                model.addAttribute("error",map);
                return "/reg";
            }else {
                redisTemplate.delete(SMSConstant.SMS_CODE_PERFIX + vo.getPhone());
                //System.out.println(vo);
                //远程调用
                R r = memberFeginService.register(vo);
                if(r.getCode() == 0){
                    //注册成功
                    return "redirect:http://auth.skd.com/login.html";
                }else {
                    //注册失败
                    map.put("msg", r.getMessage(r.getCode()));
                    model.addAttribute("error",map);
                    return "/reg";
                }
            }
        }
        // 表单提交的注册的数据是合法的
        //return "redirect:/login.html";
    }

    /**
     * 登录的方法
     * @return
     */
    @PostMapping("/login")
    public String login(LoginVo loginVo , RedirectAttributes redirectAttributes, HttpSession session){
        R r = memberFeginService.login(loginVo);
        if(r.getCode() == 0){
            String entityJson = (String) r.get("entity");
            MemberVO memberVO = JSON.parseObject(entityJson,MemberVO.class);
            session.setAttribute(AuthConstant.AUTH_SESSION_REDIS,memberVO);
            // 表示登录成功
            return "redirect:http://mall.skd.com/";
        }

        redirectAttributes.addAttribute("errors",r.get("msg"));

        // 表示登录失败,重新跳转到登录页面
        return "redirect:http://auth.skd.com/login.html";


    }
}
